const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
    data: {
      id_number:'',
      address: '',
      postalCode: '',
      recipientName: '',
      is_certificate_issued:'',
      recognitionResult: '',
      
      certificateOptions:[{name:"否"},{name:"是"}],
      certificateIndex:null,

      recording: false,  // 用于标记当前是否正在录音
      isPaused: false,   // 用于标记录音是否处于暂停状态
      recordFilePath: '',  // 用于保存录音文件的临时路径
      editableContent: '', // 用于保存识别后文本内容的初始化
      buttonText: '开始录音', // 新增按钮文本控制变量
    },

    onLoad(){
        const storaged_post_info = wx.getStorageSync('post_candidate_info');
        this.setData({
            id_number:storaged_post_info.id_number,
            address: storaged_post_info.address,
            postalCode: storaged_post_info.postal_code,
            recipientName: storaged_post_info.recipient_name,
            is_certificate_issued:storaged_post_info.is_certificate_issued,
            certificateIndex:tools.findIndexByName(this.data.certificateOptions,storaged_post_info.is_certificate_issued)
        })
    },
    bindAddressInput: function(e) {
      this.setData({
        address: e.detail.value
      });
    },
    bindPostalCodeInput: function(e) {
      this.setData({
        postalCode: e.detail.value
      });
    },
    bindRecipientNameInput: function(e) {
      this.setData({
        recipientName: e.detail.value
      });
    },
    handlePickerChange: function(e){
      const index = e.detail.value;
      const name = this.data.certificateOptions[index].name;
      this.setData({
        certificateIndex:index,
        is_certificate_issued:name
      })
    },
    handleSubmit: function() {
      const { address, postalCode, recipientName } = this.data;
      if (!address || !postalCode || !recipientName) {
        wx.showToast({
          title: '请填写所有信息',
          icon: 'none'
        });
        return;
      }
      const fieldsToCheck = [
        'id_number',
        'address',
        'postal_code',
        'recipient_name',
        'is_certificate_issued'
      ];
      const postData={
        "id_number" :this.data.id_number,
        address:this.data.address,
        postal_code :this.data.postalCode,
        recipient_name:this.data.recipientName,
        is_certificate_issued:this.data.is_certificate_issued
      }
      if(tools.checkDataChanged(postData,wx.getStorageSync('post_candidate_info'),fieldsToCheck)){
        http.post('/candidate/updateNotificationInfo', postData).then(res =>{
          if (res.data.code === 200) {
              wx.setStorageSync('post_candidate_info', postData);
              wx.showToast({ title: '邮寄信息更新成功', duration: 3000 });
              wx.reLaunch({
                url: '/pages/zhuanshengben/zsb_exam_registrationInfo/zsb_exam_registrationInfo',
              })
            }
        }).catch(err => {
          console.error('邮寄信息更新失败:', err);
          wx.showToast({ title: '邮寄信息更新失败', icon: 'none' });
        });
      }else{
        wx.reLaunch({
          url: '/pages/zhuanshengben/zsb_exam_registrationInfo/zsb_exam_registrationInfo',
        })
      }
    },
    // 录音功能区
    // 录音按键
    toggleRecording() {
      // const that = this;
      if (this.data.recording) {
          // 停止录音逻辑
          this.setData({ recording: false });
          const recorderManager = wx.getRecorderManager();
          recorderManager.stop();
          recorderManager.onStop((res) => {
              // 将录音文件临时路径存储到本地存储
              wx.setStorageSync('recordPath', res.tempFilePath);
              this.setData({ recordFilePath: res.tempFilePath });
              // 这里调用后端代码进行录音转文字
              // that.setData({ editableContent: '转换后的文本内容' });
              this.setData({ buttonText: '开始录音' });
          });
      } else {
          tools.checkRecordPermission().then(() => {
              // 开始录音逻辑
              this.setData({ recording: true });
              const recorderManager = wx.getRecorderManager();
              recorderManager.start({
                  format: 'wav', // 设置为wav格式
                  duration: 60000, 
                  sampleRate: 44100, 
                  numberOfChannels: 1, 
                  encodeBitRate: 96000
              });
              this.setData({ buttonText: '停止录音' });
          }).catch((error) => {
              wx.showToast({
                  title: error,
                  icon:'none'
              });
          });
      }
    },
  
  // 上传录音并进行语音识别函数
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
        wx.showToast({ title: '请先录制录音', icon: 'none' });
        return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.zsbExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        this.updateInfo(res.data)
        // this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },
  updateInfo(dataFields){
    const fields = {
        address: 'address',
        postalCode: 'postal_code',
        recipientName: 'recipient_name'
      }
      // console.log(dataFields);
      Object.entries(fields).forEach(([key,value]) =>{
          // console.log(key)
          // console.log(dataFields[value])
          if(!dataFields[value].includes("未知")){
              this.setData({
                  [key] : dataFields[value]
              })
          }
      })
      // 对是否获得证书进行修改
      if(!dataFields['is_certificate_issued'].includes("未知")){
        if(dataFields['is_certificate_issued']=="1"){
          this.setData({
            is_certificate_issued : '是'
          })
        }}else{
          this.setData({
            is_certificate_issued : '否'
          })
        }
        this.setData({
          certificateIndex:parseInt(dataFields['is_certificate_issued'])
        })
  }
  });